package com.hospitalmanagementsystem.controller;

import com.hospitalmanagementsystem.dto.AppointmentDTO;
import com.hospitalmanagementsystem.dto.DoctorDTO;
import com.hospitalmanagementsystem.service.AppointmentService;
import com.hospitalmanagementsystem.service.DoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
// import org.springframework.security.core.userdetails.UserDetails; // No longer directly needed for username
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/doctors")
public class DoctorController {

    private final DoctorService doctorService;
    private final AppointmentService appointmentService;

    @Autowired
    public DoctorController(DoctorService doctorService, AppointmentService appointmentService) {
        this.doctorService = doctorService;
        this.appointmentService = appointmentService;
    }

    /**
     * 获取当前登录的医生的个人信息
     * @return 医生信息
     */
    @GetMapping("/profile")
    public ResponseEntity<DoctorDTO> getCurrentDoctorProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = getUserIdFromAuthentication(authentication);
        DoctorDTO doctor = doctorService.getDoctorByUserId(userId);
        return ResponseEntity.ok(doctor);
    }

    /**
     * 更新当前登录的医生的个人信息
     * @param doctorDTO 医生信息
     * @return 更新后的医生信息
     */
    @PutMapping("/profile")
    public ResponseEntity<DoctorDTO> updateCurrentDoctorProfile(@RequestBody DoctorDTO doctorDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = getUserIdFromAuthentication(authentication);
        
        // 获取医生ID
        DoctorDTO currentDoctor = doctorService.getDoctorByUserId(userId);
        
        // 确保只能修改自己的信息，设置正确的ID
        doctorDTO.setId(currentDoctor.getId());
        doctorDTO.setUserId(userId);
        
        DoctorDTO updatedDoctor = doctorService.updateDoctor(currentDoctor.getId(), doctorDTO);
        return ResponseEntity.ok(updatedDoctor);
    }

    /**
     * 获取当前登录医生的预约列表
     * @return 预约列表
     */
    @GetMapping("/appointments")
    public ResponseEntity<List<AppointmentDTO>> getCurrentDoctorAppointments() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = getUserIdFromAuthentication(authentication);
        
        // 获取医生ID
        DoctorDTO doctor = doctorService.getDoctorByUserId(userId);
        
        List<AppointmentDTO> appointments = appointmentService.getAppointmentsByDoctorId(doctor.getId());
        return ResponseEntity.ok(appointments);
    }

    /**
     * 更新预约状态
     * @param appointmentId 预约ID
     * @param status 预约状态
     * @return 更新后的预约信息
     */
    @PutMapping("/appointments/{appointmentId}/status")
    public ResponseEntity<AppointmentDTO> updateAppointmentStatus(
            @PathVariable Long appointmentId,
            @RequestParam String status) {
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long doctorUserId = getUserIdFromAuthentication(authentication);
        
        // 获取医生ID
        DoctorDTO doctor = doctorService.getDoctorByUserId(doctorUserId);
        
        // 获取预约信息，确认该预约是分配给当前医生的
        AppointmentDTO appointment = appointmentService.getAppointmentById(appointmentId);
        if (!appointment.getDoctorId().equals(doctor.getId())) {
            // Consider throwing a more specific exception or returning a 403 Forbidden
            return ResponseEntity.status(403).body(null); // Or some error DTO
        }
        
        // 更新预约状态
        AppointmentDTO updatedAppointment = appointmentService.updateAppointmentStatus(
            appointmentId, 
            com.hospitalmanagementsystem.enums.AppointmentStatus.valueOf(status.toUpperCase())
        );
        
        return ResponseEntity.ok(updatedAppointment);
    }

    private Long getUserIdFromAuthentication(Authentication authentication) {
        if (authentication == null || authentication.getDetails() == null) {
            throw new IllegalStateException("Authentication or authentication details are missing.");
        }

        if (authentication.getDetails() instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> detailsMap = (Map<String, Object>) authentication.getDetails();
            Object userIdObj = detailsMap.get("userId");

            if (userIdObj instanceof Number) {
                return ((Number) userIdObj).longValue();
            } else if (userIdObj != null) {
                // Attempt to parse if it's a String representation of a number, though it should be Long from claims
                try {
                    return Long.parseLong(userIdObj.toString());
                } catch (NumberFormatException e) {
                    throw new IllegalStateException("User ID in authentication details is not a valid number: " + userIdObj, e);
                }
            } else {
                throw new IllegalStateException("User ID (userId) not found in authentication details map.");
            }
        } else {
            throw new IllegalStateException("Authentication details are not a Map. Actual type: " + authentication.getDetails().getClass().getName());
        }
    }
} 